<template>
	<view>
		<view class="address-container">
			<view class="from">
				<text>{{ from.address }}</text>
			</view>
			<view class="dashed-line"></view>
			<view class="to">
				<text>{{ to.address }}</text>
			</view>
		</view>
		<view v-if="inPorcessOrderId != null" class="order-process" @click="toInProcessOrder">您有进行中的订单,点击查看</view>
		<map id="map" :longitude="from.longitude" :latitude="from.latitude" :style="contentStyle" scale="16"
			:enable-traffic="false" :show-location="true" class="map" :polyline="polyline" :markers="markers"></map>

		<view class="panel">
			<view class="row">
				<view class="info">
					<view class="label">全程</view>
					<view class="value">
						<text>{{ distance }}</text>
						公里
					</view>
					<view class="label">，预计</view>
					<view class="value">
						<text>{{ duration }}</text>
						分钟
					</view>
				</view>
				<view class="opt" @tap="chooseCarHandle" v-if="!showCar">选择车辆</view>
				<view class="opt" @tap="chooseCarHandle" v-if="showCar">{{ car.carType }}&emsp;{{ car.carPlate }}</view>
			</view>
			<button class="btn" @tap="createOrderHandle">确定下单</button>
		</view>
		<u-popup v-model="showPopup" mode="center" width="600" height="280" :mask-close-able="false">
			<view class="popup-title">您的订单正在等待司机接单</view>
			<view class="count-down">
				<u-count-down ref="uCountDown" :timestamp="timestamp" :autoplay="false" separator="zh"
					:show-hours="false" :show-border="true" bg-color="#DDF0FF" separator-color="#0083F3"
					border-color="#0D90FF" color="#0D90FF" font-size="32" @end="countEndHandle"
					@change="countChangeHandle"></u-count-down>
				<!-- @change="countChangeHandle" -->
			</view>
			<button class="btn" @tap="countEndHandle">取消订单</button>
		</u-popup>
		<u-top-tips ref="uTips"></u-top-tips>
		<u-modal v-model="uModalShow" show-confirm-button="继续等待" show-cancel-button="确定取消" @confirm="confirm"
			ref="uModal" :async-close="true"></u-modal>

	</view>
</template>

<script>
	let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
	let qqmapsdk;
	export default {
		data() {
			return {
				//订单路线：开始位置和结束位子
				from: {
					address: '',
					longitude: 0,
					latitude: 0
				},
				to: {
					address: '',
					longitude: 0,
					latitude: 0
				},
				//窗口样式
				contentStyle: '',
				windowHeight: 0,
				//距离和时长
				distance: 0,
				duration: 0,
				//路线规划，路线坐标和图标
				polyline: [],
				markers: [],

				//
				infoStatus: true,
				car: {
					//乘客选择的车辆
					carId: null,
					carPlate: null,
					carType: null,
				},
				showCar: false,
				showPopup: false,
				timestamp: 60,
				timestampStaring: false,
				orderNo: null,
				//地图组件
				map: null,
				//接单的定时任务
				acceptOrderTimer: null,
				uModalShow: false,
				//是否有进行中的订单
				inPorcessOrderId: null
			};
		},
		methods: {
			loadInProcessOrder(){
				let _this = this;
				_this.get("/order/app/order/customer/inprocess", (res) => {
					let {
						success,
						data
					} = res.data;
					if (success && data) {
						console.log(data);
						_this.orderNo = data.orderNo
						// 如果有进行中的订单则 跳转创建订单页 create_order.vue
						if (data.status == _this.orderStatus.ORDER_STATUS_WAIT) {
							_this.showPopup = true;
							_this.$refs.uCountDown.start();
						} else if (data.status == _this.orderStatus.ORDER_STATUS_ACCEPTED ||
							data.status == _this.orderStatus.ORDER_STATUS_ARRIVE ||
							data.status == _this.orderStatus.ORDER_STATUS_START_DRIVING) {
							// 如果是 1接单  2司机到达 3开始代驾  则跳转司乘同显
							uni.navigateTo({
								url: "/pages/move/move?orderNo=" + _this.orderNo
							})
						} else {
							// 如果是 4结束代驾，5.司机确认费用，6未付款 , 则跳转订单详情页
							uni.navigateTo({
								url: "/pages/order/order?orderNo=" + _this.orderNo
							})
						}
				
					}
				})
			},
			// 倒计时改变
			countChangeHandle(timestamp) {
				let _this = this;
				// 5秒一次， 检查订单是否已经被接单
				if (timestamp % 5 == 0 || timestamp == 3) {
					_this.get("/order/app/order/customer/inprocess", (res) => {
						let {
							success,
							data
						} = res.data;
						if (success && data) {
							console.log(data);
							//订单号赋值
							_this.orderNo = data.orderNo
							// 如果有进行中的订单则 跳转创建订单页 create_order.vue
							if (data.status == _this.orderStatus.ORDER_STATUS_ACCEPTED ||
								data.status == _this.orderStatus.ORDER_STATUS_ARRIVE ||
								data.status == _this.orderStatus.ORDER_STATUS_START_DRIVING) {
								//订单未接单，跳转创建页
								_this.showPopup = false;
								_this.timestamp = 0;
								// 如果是 1接单  2司机到达 3开始代驾  则跳转司乘同显
								uni.navigateTo({
									url: "/pages/move/move?orderNo=" + _this.orderNo
								})
							}
							// // 如果司机取消订单
							// if (data.status == _this.orderStatus.ORDER_STATUS_DRIVER_CANCEL_ORDER) {
							// 	//订单被司机取消，需要重新下单
							// 	_this.showPopup = false;
							// 	_this.timestamp = 0;
			
							// }
						}
					})
			
				}
			},
			
			// 自动取消订单(手动取消订单也行)
			countEndHandle(){
				let _this = this;
				if(!_this.orderNo) return;
				_this.post("/order/app/order/autoCancelOrder/"+_this.orderNo,(res)=>{
					let {success,data} = res.data;
					if(success){
						uni.showToast({
							title: "订单取消成功",
							icon: "success"
						})
						// 关闭倒计时模态框
						_this.showPopup = false;
						_this.timestamp = 0;
						
					}else{
						uni.showToast({
							title :"订单取消失败,请稍后",
							icon: "error"
						})
					}
				})
			},
			// 开始下单
			createOrderHandle(){
				let _this = this
				let param = {
					// 开始位置
					startPlace: _this.from.address,
					startPlaceLongitude: _this.from.longitude,
					startPlaceLatitude: _this.from.latitude,
					// 结束位置
					endPlace: _this.to.address,
					endPlaceLongitude: _this.to.longitude,
					endPlaceLatiude: _this.to.latitude,
					//距离和时长
					expectsMileage: _this.distance,
					expectMinutes: _this.duration,
					//乘客选择的车辆
					carPlate: _this.car.carPlate,
					carType: _this.car.carType,
				}
				_this.post("/order/app/order/createOrder",param,(res)=>{
					let {success,data,message}=res.data
					if(success){
						_this.orderNo = data;
						// 显示倒计时模态框
						_this.showPopup = true
						// 启动倒计时
						_this.$refs.uCountDown.start();
						// 设置倒计时时间
						_this.timestamp = 30;
					}
					// else{
					// 	uni.showToast({
					// 		title :message,
					// 		icon: "error"
					// 	})
					// }
				})
			},

			// 选择车辆
			chooseCarHandle() {
				let _this = this;
				uni.navigateTo({
					url: "/pages/car_list/car_list"
				})
			},
			//初始化窗口样式
			initStyle() {
				let _this = this;
				//处理窗口样式
				let windowHeight = uni.getSystemInfoSync().windowHeight;
				_this.windowHeight = windowHeight;
				_this.contentStyle = `height:${_this.windowHeight}px;`;
			},
			// 路线规划
			initRoutePlanner() {
				var _this = this;
				//调用距离计算接口
				qqmapsdk.direction({
					mode: 'driving', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
					//from参数不填默认当前地址
					from: _this.from,
					to: _this.to,
					success: function(res) {
						var ret = res;
						var coors = ret.result.routes[0].polyline,
							pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						var kr = 1000000;
						for (var i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						}
						//将解压后的坐标放入点串数组pl中
						for (var i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						}
						// 设置预估距离和时长
						_this.distance = ret.result.routes[0].distance / 1000
						_this.duration = ret.result.routes[0].duration
						//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点						
						// 规划路线
						_this.polyline = [{
							points: pl,
							color: '#FF0000DD',
							width: 4
						}]
						// 设置坐标点
						_this.markers = [{
								id: 1,
								title: "开始位置标记",
								longitude: _this.from.longitude,
								latitude: _this.from.latitude,
								iconPath: "/static/order/start.png"
							},
							{
								id: 2,
								title: "结束位置标记",
								longitude: _this.to.longitude,
								latitude: _this.to.latitude,
								iconPath: "/static/order/end.png"
							},
						]

					},
					fail: function(error) {
						uni.showToast({
							title: "路线绘制失败",
							icon: "error"
						})
					},
					// complete: function(res) {
					// 	console.log(res);
					// }
				});
			},
			// 初始化地图
			initMap() {
				let _this = this;
				_this.map = uni.createMapContext("map", this)
				_this.getLocation()
			},
			// 获取腾讯地图中密钥Key
			initQQMapWx() {
				let _this = this;
				qqmapsdk = new QQMapWX({
					key: _this.Consts.QQMAP_KEY // 必填
				});
			},
			//获取当前位置经纬度
			getLocation() {
				let _this = this;
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						let location = {
							latitude: res.latitude,
							longitude: res.longitude
						}
					},
					fail: function(error) {
						uni.showToast({
							icon: "error",
							title: "定位失败"
						})
					}
				});
			},

		},
		onLoad: function(options) {
			let _this = this;
			_this.initStyle();
		},
		onShow: function() {
			let _this = this;
			// 初始化地图
			_this.initMap()
			// 获取腾讯地图中的密钥
			_this.initQQMapWx();
			_this.from = uni.getStorageSync("from")
			_this.to = uni.getStorageSync("to")
			// 路线规划
			_this.initRoutePlanner();
			_this.car = uni.getStorageSync("car")
			if (_this.car) {
				_this.showCar = true
			}
			//加载乘客进行中的订单
			_this.loadInProcessOrder();

		},
		onUnload() {}
	};
</script>

<style lang="less">
	@import url('create_order.less');
</style>